<?php


namespace app\index\controller;


use app\model\Boutcardorder;
use app\model\Config;
use app\model\Member;
use app\model\MemberCashlogs;
use app\model\Order;
use app\model\Paymethod;
use app\model\StoreBail;
use app\model\TechnicalBail;
use app\model\Tongue;
use app\model\Viporder;
use app\model\Wxpay;

class TtpayController extends Base
{
    public function index()
    {
        $orderid = intval(input('post.orderid'));
        $money = input('post.money');
        $money = round($money, 2);
        $money = floatval($money * 100);

        $type = input('post.type');
        if ($type == "order") {
            if (!empty($orderid)) {
                $orderdata = Order::find($orderid);
                if (!empty($orderdata)) {
                    $orderdata = $orderdata->toArray();

                    if ($orderdata['is_user_send'] == 1 &&
                        $orderdata['order_status_id'] == 1 &&
                        $orderdata['ptype'] == 2 &&
                        $orderdata['price_type'] == 1 &&
                        $orderdata['is_select_quotation'] == 0
                    ) {
                        return $this->json(['errno' => 1, 'msg' => '请先选择师傅']);
                    }
                } else {
                    return $this->json(['errno' => 1, 'msg' => '订单不存在']);
                }

                //构造支付参数
                $paydata = array(
                    'subject' => '订单支付',
                    'body' => '订单支付',
                    'out_order_no' => (string)$orderid,
                    'total_amount' => $money,
                );
            }
        } elseif ($type == "vip") {
            $paydata = array(

                'subject' => '购买会员等级',
                'body' => '购买会员等级',
                'out_order_no' => 'vip-' . $orderid . '-' . time(),
                'total_amount' => $money,
            );
        } elseif ($type == "additional") {
            if (!empty($orderid)) {
                $orderdata = Order::find($orderid);
                if (!empty($orderdata)) {
                    $orderdata = $orderdata->toArray();
                } else {
                    return $this->json(['errno' => 1, 'msg' => '订单不存在']);
                }

                //构造支付参数
                $paydata = array(
                    'subject' => '支付尾款',
                    'body' => '支付尾款',
                    'out_order_no' => 'additional-' . $orderid,
                    'total_amount' => $money,
                );
            }
        } elseif ($type == "paybill") {
            $paydata = array(
                'subject' => '优惠买单',
                'body' => '优惠买单',
                'out_order_no' => 'paybill-' . time(),
                'total_amount' => $money,
            );
        } elseif ($type == "recharge") {

            $paydata = array(
                'subject' => '充值',
                'body' => '充值',
                'out_order_no' => 'recharge-' . UID() . "-" . time(),
                'total_amount' => $money,
            );
        } elseif ($type == "tongue") {

            $paydata = array(
                'subject' => 'AI舌诊',
                'body' => 'AI舌诊',
                'out_order_no' => 'tongue-' . $orderid,
                'total_amount' => $money,
            );
        } elseif ($type == 'boutorder') {
            $paydata = array(
                'subject' => '次卡订单',
                'body' => '次卡订单',
                'out_order_no' => 'boutcard-' . $orderid,
                'total_amount' => $money,
            );
        } elseif ($type == 'technicalbail') {
            $paydata = array(
                'subject' => '师傅保证金',
                'body' => '师傅保证金',
                'out_order_no' => 'technicalbail-' . $orderid,
                'total_amount' => $money,
            );
        } elseif ($type == 'storebail') {
            $paydata = array(
                'subject' => '商家保证金',
                'body' => '商家保证金',
                'out_order_no' => 'storebail-' . $orderid,
                'total_amount' => $money,
            );
        }
        $paydata['valid_time'] = 900;
        //生成支付参数，返回给小程序端

        $pay_params = $this->dopay($paydata);
        $data = json_decode($pay_params, true);
        return $this->json(['data' => isset($data['data']) ? $data['data'] : []]);
    }

    public function dopay($paydata)
    {
        $app_id = Config::getconfig('miniprogram')['ttapp_id'];
        $settings = Paymethod::tt_settings();
        $paydata['app_id'] = $app_id;
        $paydata['notify_url'] = gethost() . TP_APIURL . '/index.php/index/ttpay/notify';
        $paydata['sign'] = $this->sign($paydata, $settings['salt']);

        $url = "https://developer.toutiao.com/api/apps/ecpay/v1/create_order";
        return $this->json_post($url, $paydata);
    }


    function json_post($url, $data = NULL)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!$data) {
            return 'data is null';
        }
        if (is_array($data)) {
            $data = json_encode($data, 320);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length:' . strlen($data),
            'Cache-Control: no-cache',
            'Pragma: no-cache'
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

    //支付回调
    public function notify()
    {
        header("Content-type: text/plain; charset=utf-8");
        $content = file_get_contents('php://input');
        file_put_contents(__DIR__ . "/../../../runtime/log/backdata.txt", $content); //数据写入文件
        $content = json_decode($content, true);
        $settings = Paymethod::tt_settings();
        $rList = [];
        array_push($rList, $settings['token']);
        foreach ($content as $k => $v) {
            if ($k == "type" || $k == 'msg_signature')
                continue;
            $value = trim(strval($v));
            if ($value == "" || $value == "null")
                continue;
            array_push($rList, $value);
        }
        sort($rList, 2);

        if (sha1(implode($rList)) != $content['msg_signature']) {
            return 'error';
        }
        $msg = json_decode($content['msg'], true);
        if ($msg['status'] === 'SUCCESS') {
            $tid = $msg['cp_orderno'];
            $tidarray = explode('-', $tid);
            $message['pay_amt'] = $msg['total_amount'] / 100;
            if (!empty($tidarray[1])) {
                $tid = $tidarray[1];
            }
            if ($tidarray[0] == 'paybill') {
                $cashlogsdata['uid'] = UID();
                $cashlogsdata['uniacid'] = uniacid();
                $cashlogsdata['id'] = '0';
                $cashlogsdata['order_num_alias'] = '0';
                $cashlogsdata['remarks'] = '优惠买单';
                $cashlogsdata['prefix'] = 2;
                $cashlogsdata['amount'] = $message['pay_amt'];
                $cashlogsdata['create_time'] = time();
                MemberCashlogs::create($cashlogsdata);
            } elseif ($tidarray[0] == 'recharge') {
                Member::where('id', $tid)
                    ->inc('balance', $message['pay_amt'])
                    ->update();
                $cashlogsdata['uid'] = $tid;
                $cashlogsdata['uniacid'] = uniacid();
                $cashlogsdata['id'] = '0';
                $cashlogsdata['order_num_alias'] = '0';
                $cashlogsdata['remarks'] = '充值';
                $cashlogsdata['prefix'] = 1;
                $cashlogsdata['amount'] = $message['pay_amt'];
                $cashlogsdata['create_time'] = time();
                MemberCashlogs::create($cashlogsdata);
            } elseif ($tidarray[0] == 'additional') {
                Order::itional_pay($tid);
            } elseif ($tidarray[0] == 'tongue') {
                Tongue::where('id', $tid)->update(['is_pay' => 1]);
            } elseif ($tidarray[0] == 'vip') {
                Viporder::pay_order(['id' => $tid]);
            } elseif ($tidarray[0] == 'boutcard') {
                $data['id'] = $tid;
                $data['payment_code'] = 'tt_pay';
                Boutcardorder::pay_order($data);
            } elseif ($tidarray[0] == 'technicalbail') {
                $data['id'] = $tid;
                TechnicalBail::pay_order($data);
            } elseif ($tidarray[0] == 'storebail') {
                $data['id'] = $tid;
                StoreBail::pay_order($data);
            } else {
                $fee = $message['pay_amt'];
                if (!empty($fee)) {
                    $order = Order::find($tid);
                    if (!empty($order)) {
                        $order = $order->toArray();
                    }
                }
                $data['id'] = $tid;
                $data['user_agent'] = serialize($message);
                $data['payment_code'] = 'tt_pay';
                $ordermod = new Order;
                $ordermod->pay_order($data);
            }
            $res = ['err_no' => 0, 'err_tips' => 'success'];
            echo json_encode($res);
            die;
        }

    }

    function sign($map, $salt)
    {
        $rList = array();
        foreach ($map as $k => $v) {
            if ($k == "other_settle_params" || $k == "app_id" || $k == "sign" || $k == "thirdparty_id")
                continue;
            $value = trim(strval($v));
            $len = strlen($value);
            if ($len > 1 && substr($value, 0, 1) == "\"" && substr($value, $len, $len - 1) == "\"")
                $value = substr($value, 1, $len - 1);
            $value = trim($value);
            if ($value == "" || $value == "null")
                continue;
            array_push($rList, $value);
        }
        array_push($rList, $salt);
        sort($rList, 2);
        return md5(implode('&', $rList));
    }
}



